package admin

import (
	"ginBasic/app/common/lib"
	"net/http"

	"github.com/gin-gonic/gin"

	"ginBasic/app/common/business"
	"ginBasic/app/common/model"
	"ginBasic/app/common/model/filter"
)

type AccessController struct {
	BaseController
}

func (con AccessController) Index(c *gin.Context) {
	c.HTML(http.StatusOK, "admin/access/index.html", gin.H{})
}

func (con AccessController) GetList(c *gin.Context) {

	var req *filter.AccessFilterReq
	reqErr := c.ShouldBind(&req)
	if reqErr != nil {
		con.ShowRes(-1, reqErr.Error(), c)
		return
	}
	list, total, resErr := business.Access.GetList(req)
	if resErr != nil {
		con.ShowRes(-1, resErr.Error(), c)
		return
	}
	con.Show(0, total, list, "查询成功", c)
	return
}

func (con AccessController) Add(c *gin.Context) {
	accessList, _, _ := business.Access.GetList(&filter.AccessFilterReq{Type: 1})
	//bytes, _ := json.MarshalIndent(list, "", "    ")
	//fmt.Printf("%s\n", bytes)
	c.HTML(http.StatusOK, "admin/access/add.html", gin.H{
		"accessList": accessList,
	})
}

func (con AccessController) DoAdd(c *gin.Context) {
	if c.Request.Method != "POST" {
		con.ShowRes(-1, "请求方式有误", c)
		return
	}
	var req *model.Access
	reqErr := c.ShouldBind(&req)
	if reqErr != nil {
		con.ShowRes(-1, reqErr.Error(), c)
		return
	}
	_, err := business.Access.Add(req)
	if err != nil {
		con.ShowRes(-1, reqErr.Error(), c)
		return
	} else {
		con.ShowRes(0, "操作成功", c)
		return
	}
}

func (con AccessController) Edit(c *gin.Context) {
	id, reqErr := lib.Int(c.Query("id"))
	if reqErr != nil {
		con.ShowRes(-1, reqErr.Error(), c)
		return
	}
	accessList, _, _ := business.Access.GetList(&filter.AccessFilterReq{Type: 1})
	accessInfo := business.Access.GetInfoById(id)
	c.HTML(http.StatusOK, "admin/access/edit.html", gin.H{
		"accessList": accessList,
		"accessInfo": accessInfo,
	})
}

func (con AccessController) DoEdit(c *gin.Context) {
	if c.Request.Method != "POST" {
		con.ShowRes(-1, "请求方式有误", c)
		return
	}
	var req *model.Access
	reqErr := c.ShouldBind(&req)
	if reqErr != nil {
		con.ShowRes(-1, reqErr.Error(), c)
		return
	}
	_, err := business.Access.Edit(req)
	if err != nil {
		con.ShowRes(-1, reqErr.Error(), c)
		return
	} else {
		con.ShowRes(0, "操作成功", c)
		return
	}
}

func (con AccessController) Del(c *gin.Context) {
	id, reqErr := lib.Int(c.Query("id"))
	if reqErr != nil {
		con.ShowRes(-1, "记录ID不能为空", c)
		return
	}
	err := business.Access.Delete(id)
	if err != nil {
		con.ShowRes(-1, err.Error(), c)
		return
	} else {
		con.ShowRes(0, "成功删除1条数据", c)
		return
	}
}
